# -*- coding:utf-8 -*-
"""
配置（定时读取配置）文件
"""
from os import path
import os
import json
import threading
import time
import datetime
from threading import Timer
import re
# from utilities.log_help import LogHelper,TraceHelper,DebugHelper

class Singleton(object):
    _instance_lock = threading.Lock()

    def __init__(self, *args, **kwargs):
        # time.sleep(1)
        pass

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            with Singleton._instance_lock:
                if not hasattr(cls, '_instance'):
                    Singleton._instance = super().__new__(cls)
        return Singleton._instance





class Config(Singleton):

    def __init__(self):
        if not hasattr(self, '_instance_init'):
            self._instance_init = True
            self.interval_time = 60
            self.version = None
            # self.loghelper = LogHelper("Config","/opt/logs","nlp_show_interface.log")
            self.real_time_update()

        # pass


    def loads_on_off(self, config_file=None):
        """ Load config file.

        Args:
            config_file: config json file.
        """
        configures = {}
        if config_file:
            # try:
            with open(config_file,encoding='utf-8') as f:
                data = f.read()
                configures = json.loads(data)

            # except Exception as e:
            #     print(e)
                # exit(0)
            if not configures:
                print("config json file error!")
                # exit(0)
            
        return configures.get("version",None)


    def loads(self, config_file=None):
        """ Load config file.

        Args:
            config_file: config json file.
        """
        configures = {}
        if config_file:
            try:
                with open(config_file,encoding='utf-8') as f:
                    data = f.read()
                    configures = json.loads(data)
                    # self.loghelper.log_info( transaction_id="transaction_id", user="self", msg_info=r'更新配置', value=data ,location_code = "config.py#loads#202102031526#80")

            except Exception as e:
                print(e)
                # exit(0)
            if not configures:
                print("config json file error!")
                # exit(0)
        self._update(configures)

    # 每隔两秒执行一次任务
    def real_time_update(self):
        # print('TimeNow:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
        # print(threading.get_ident())
        # print(threading.current_thread().name)
        # print(threading.current_thread().ident)
        # print(threading.get_ident())
        # tversion = self.loads_on_off("/home/zhibin/gitlab_biz/biz-dm-process-v3/flask_restful_project/manual_config/config_data/config_on-of.json")
        lpath = path.join('manual_config','config_data','config_on-of.json')
        # lpath = path.join('config_data','config_on-of.json')
        # tversion = self.loads_on_off("manual_config/config_data/config_on-of.json")
        print(os.getcwd())
        tversion = self.loads_on_off(lpath)
        if  tversion and tversion!=self.version:
            print("********************")
            # self.loads("/home/zhibin/gitlab_biz/biz-dm-process-v3/flask_restful_project/manual_config/config_data/config.json")
            # self.loads("manual_config/config_data/config.json")
            lpath = path.join('manual_config','config_data','config.json')
            # lpath = path.join('config_data','config.json')
            self.loads(lpath)
            self.version = tversion
        if self.interval_time:
            t = Timer(self.interval_time, self.real_time_update)
            t.start()        

    def _update(self, update_fields):
        """
        更新update fields.
        :param update_fields:
        :return: None

        """

        for k, v in update_fields.items():
            setattr(self, k, v)

Manual_config = Config()

# config1 = Config()

if __name__ == "__main__":
    # config.real_time_update()
    # config.loads("config.json")

    '''
    使用方法，
    1、应用本模块
    from manual_config import Manual_config
    2、获取参数
    a = getattr(Manual_config,"config","g1")

    '''

    a = getattr(Manual_config,"config","g1")
    b = getattr(Manual_config,"scene_corresponding_table","g")
    print(a,type(a))
    print(b,type(b))

    # a1 = getattr(config1,"config","g")
    # b1 = getattr(config1,"bb","g")
    # print(a1,type(a1))
    # print(b1,type(b1))

    while True:
        a = getattr(Manual_config,"config","g1")
        b = getattr(Manual_config,"scene_botid_table","g")
        print(a,type(a))
        print(b,type(b))


        time.sleep(15)